import { defineStore } from "pinia";
import { ref } from "vue";
import {
  getLoginUserUsingGet,
  userLogoutUsingPost,
} from "@/api/userController";
import AccessEnum from "@/access/accessEnum";
import { useRouter } from "vue-router";

/**
 * 登录用户信息全局状态保存
 */
export const userLoginStore = defineStore("loginUser", () => {
  const router = useRouter();
  //变量记录当前用户
  const loginUser = ref<API.LoginUserVO>({
    userName: "未登录",
  });

  //设置当前用户状态
  function setloginUser(newLoginUser: API.LoginUserVO) {
    loginUser.value = newLoginUser;
  }

  async function fetchLoginUser() {
    const res = await getLoginUserUsingGet();
    if (res.data.code === 0 && res.data.data) {
      setloginUser(res.data.data);
    } else {
      loginUser.value.userRole = AccessEnum.NOT_LOGIN;
    }
  }

  async function LoginoutUser() {
    const res = await userLogoutUsingPost();
    if (res.data.code === 0) {
      loginUser.value.userRole = AccessEnum.NOT_LOGIN;
    }
    // 重定向用户到登录页面
    router.push(`/user/login`);
  }

  return { loginUser, setloginUser, fetchLoginUser, LoginoutUser };
});
